package boot

import (
	_ "embed"
	"fmt"
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"io/ioutil"
	"log"
	"os"
	"oss-api/library/utils"
	"time"
)

var (
	DB        *gorm.DB
	Config    OssConfig
	IdBuilder *utils.Snowflake
)

//go:embed banner.txt
var banner string

// OutputBanner 输出Banner
func OutputBanner() {
	fmt.Println(banner)
}

// InitDB 初始化DB
func InitDB() *gorm.DB {
	//dsn := "root:123456@tcp(192.168.31.138:3306)/oss-cloud?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(Config.Database.Base.Link), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   Config.Database.Base.Prefix,
			SingularTable: Config.Database.Base.Singular,
		},
		PrepareStmt:          true,
		DisableAutomaticPing: Config.Database.Base.AutoPing,
		Logger: logger.New(
			log.New(os.Stdout, "[oss-cloud-sql] ", log.LstdFlags),
			logger.Config{
				SlowThreshold:             time.Second * 1,
				LogLevel:                  Config.Database.Logger.GetLevel(),
				IgnoreRecordNotFoundError: true,
				Colorful:                  Config.Database.Logger.Color,
			},
		),
	})
	if err != nil {
		panic(fmt.Sprintf("获取数据库连接失败: %s\n", err))
	}
	sqlDB, err := db.DB()
	if err != nil {
		panic(fmt.Sprintf("配置连接池失败: %s\n", err))
	}
	sqlDB.SetMaxIdleConns(Config.Database.Base.MaxIdleConns)
	sqlDB.SetMaxOpenConns(Config.Database.Base.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Hour)
	fmt.Printf("[oss-api] %s [INFO] : 初始化DB配置完成\n", time.Now().Format("2006-01-02 15:04:05"))

	//db.AutoMigrate(&model.Resource{})
	//db.AutoMigrate(&model.Category{})

	return db
}

// initConfig 初始化配置信息
func initConfig() OssConfig {
	fmt.Printf("[oss-api] %s [INFO] : 初始化应用配置\n", time.Now().Format("2006-01-02 15:04:05"))
	var config OssConfig
	file, err := ioutil.ReadFile("config/config.yaml")
	if err != nil {
		if os.IsNotExist(err) {
			return OssConfig{}
		}
		panic(fmt.Sprintf("解析配置文件失败: %s\n", err))
	}
	if err = yaml.Unmarshal(file, &config); err != nil {
		panic(fmt.Sprintf("解析配置文件失败: %s\n", err))
	}
	return config
}

func init() {
	OutputBanner()
	Config = initConfig()
	if Config.Database.Base.Link != "" {
		DB = InitDB()
	} else {
		fmt.Printf("[oss-api] %s [WARN] : 数据库配置缺失, 已忽略\n", time.Now().Format("2006-01-02 15:04:05"))
	}
	if Config.Server.Port == "" {
		fmt.Printf("[oss-api] %s [WARN] : 服务配置缺失, 已使用默认配置\n", time.Now().Format("2006-01-02 15:04:05"))
		Config.Server = DefaultServerConfig()
	}
	IdBuilder = utils.SnowflakeWorker(0, 0)
}
